import { http } from "@/utils/http";

/** 统一响应格式 */
export interface ApiResponse<T = any> {
  /** 状态码 */
  code: number;
  /** 响应消息 */
  message: string;
  /** 响应数据 */
  data?: T;
  /** 时间戳 */
  timestamp?: number;
}

/** 分页响应格式 */
export interface PageResponse<T> {
  /** 记录列表 */
  records: T[];
  /** 总记录数 */
  total: number;
  /** 当前页码 */
  current: number;
  /** 每页大小 */
  size: number;
  /** 总页数 */
  pages: number;
}

/** 评论状态枚举 */
export enum CommentStatus {
  /** 已删除 */
  DELETED = 0,
  /** 正常显示 */
  NORMAL = 1
}

/** 敏感词类型枚举 */
export enum SensitiveType {
  /** 脏话 */
  PROFANITY = "profanity",
  /** 政治敏感 */
  POLITICS = "politics",
  /** 广告 */
  ADVERTISEMENT = "advertisement",
  /** 暴力内容 */
  VIOLENCE = "violence",
  /** 违法内容 */
  ILLEGAL = "illegal",
  /** 垃圾信息 */
  SPAM = "spam"
}

/** 敏感词过滤模式枚举 */
export enum FilterMode {
  /** 替换模式 */
  REPLACE = "REPLACE",
  /** 拦截模式 */
  BLOCK = "BLOCK"
}

/** 批量操作类型枚举 */
export enum BatchOperationType {
  /** 删除 */
  DELETE = "delete",
  /** 标记为敏感 */
  MARK_SENSITIVE = "mark_sensitive",
  /** 取消敏感标记 */
  UNMARK_SENSITIVE = "unmark_sensitive"
}

/** 禁言类型枚举 */
export enum BanType {
  /** 禁止评论 */
  COMMENT = "COMMENT",
  /** 禁止登录 */
  LOGIN = "LOGIN",
  /** 全站禁言 */
  ALL = "ALL"
}

/** 敏感词检测结果 */
export interface SensitiveWordResult {
  /** 敏感词 */
  word: string;
  /** 类型 */
  type: string;
  /** 严重程度 (1-5) */
  severity: number;
  /** 位置 */
  position: number;
}

/** 敏感词检测响应 */
export interface SensitiveCheckResponse {
  /** 原始内容 */
  originalContent: string;
  /** 过滤后内容 */
  filteredContent: string;
  /** 是否包含敏感词 */
  hasSensitiveWords: boolean;
  /** 敏感度评分 */
  sensitiveScore: number;
  /** 主要类型 */
  primaryType: string;
  /** 敏感词列表 */
  sensitiveWords: SensitiveWordResult[];
}

/** 评论信息 */
export interface CommentInfo {
  /** 评论ID */
  id: number;
  /** 评论内容 */
  content: string;
  /** 原始内容 */
  originalContent?: string;
  /** 文章ID */
  articleId: number;
  /** 文章标题 */
  articleTitle?: string;
  /** 用户ID */
  userId: number;
  /** 用户名 */
  userName: string;
  /** 用户昵称 */
  userNickName?: string;
  /** 用户头像 */
  userAvatar?: string;
  /** 父评论ID */
  parentId: number;
  /** 根评论ID */
  rootId: number;
  /** 评论层级 */
  level: number;
  /** 评论路径 */
  path: string;
  /** 评论状态 */
  status: number;
  /** 是否敏感 */
  isSensitive: number;
  /** 敏感类型 */
  sensitiveType?: string | null;
  /** 敏感类型文本 */
  sensitiveTypeText?: string;
  /** 敏感词列表 */
  sensitiveWords?: string | null;
  /** 敏感度评分 */
  sensitiveScore?: number;
  /** IP地址 */
  ipAddress: string;
  /** 地理位置 */
  location?: string;
  /** 用户代理 */
  userAgent?: string;
  /** 点赞数 */
  likeCount: number;
  /** 回复数 */
  replyCount: number;
  /** 创建时间 */
  createTime: string;
  /** 更新时间 */
  updateTime: string;
  /** 子评论列表 */
  children?: CommentInfo[] | null;
  /** 父评论 */
  parent?: CommentInfo | null;
  /** 是否顶级评论 */
  topLevel?: boolean;
  /** 层级前缀 */
  levelPrefix?: string;
  /** 热度分数（热门评论接口返回） */
  hotScore?: number;
}

/** 评论列表查询参数 */
export interface CommentListQuery {
  /** 当前页码 */
  current?: number;
  /** 每页大小 */
  size?: number;
  /** 文章ID */
  articleId?: number;
  /** 用户ID */
  userId?: number;
  /** 用户名 */
  userName?: string;
  /** 评论内容关键词 */
  content?: string;
  /** 评论状态 */
  status?: number;
  /** 是否敏感 */
  isSensitive?: number;
  /** 敏感类型 */
  sensitiveType?: string;
  /** 父评论ID */
  parentId?: number;
  /** 根评论ID */
  rootId?: number;
  /** IP地址 */
  ipAddress?: string;
  /** 开始时间 */
  startTime?: string;
  /** 结束时间 */
  endTime?: string;
  /** 搜索关键词 */
  keyword?: string;
  /** 排序字段 */
  sortField?: string;
  /** 排序方向 */
  sortOrder?: "asc" | "desc";
  /** 只显示顶级评论 */
  onlyTopLevel?: boolean;
  /** 包含子评论 */
  includeChildren?: boolean;
  /** 最小点赞数 */
  minLikeCount?: number;
  /** 最大点赞数 */
  maxLikeCount?: number;
  /** 最小回复数 */
  minReplyCount?: number;
  /** 最大回复数 */
  maxReplyCount?: number;
}

/** 批量操作参数 */
export interface BatchOperationParams {
  /** 评论ID列表 */
  commentIds: number[];
  /** 操作类型 */
  operation: string;
  /** 备注 */
  reason?: string;
}

/** 用户禁言参数 */
export interface UserBanParams {
  /** 用户ID */
  userId: number;
  /** 禁言类型 */
  banType: BanType;
  /** 禁言时长(分钟) */
  banDuration: number;
  /** 禁言原因 */
  banReason: string;
  /** 是否永久禁言 */
  isPermanent?: boolean;
  /** 是否发送通知 */
  sendNotification?: boolean;
  /** 相关评论ID */
  relatedCommentId?: number;
}

/** 用户禁言信息 */
export interface UserBanInfo {
  /** 禁言ID */
  id: number;
  /** 禁言类型 */
  banType: BanType;
  /** 禁言原因 */
  banReason: string;
  /** 禁言开始时间 */
  banStartTime: string;
  /** 禁言结束时间 */
  banEndTime: string;
  /** 是否永久禁言 */
  isPermanent: number;
  /** 状态 */
  status: number;
}

/** 用户禁言状态 */
export interface UserBanStatus {
  /** 是否被禁言 */
  isBanned: boolean;
  /** 活跃禁言列表 */
  activeBans: UserBanInfo[];
  /** 禁言次数 */
  banCount: number;
  /** 主要禁言信息 */
  primaryBan: {
    banType: BanType;
    banDescription: string;
  };
}

/** 评论统计信息 */
export interface CommentStatistics {
  /** 总评论数 */
  totalComments: number;
  /** 已删除评论数 */
  deletedComments: number;
  /** 可见评论数 */
  visibleComments: number;
  /** 敏感评论数 */
  sensitiveComments: number;
  /** 总回复数 */
  totalReplies: number;
  /** 总点赞数 */
  totalLikes: number;
  /** 总回复数量 */
  totalReplyCount: number;
  /** 今日评论数 */
  todayComments: number;
  /** 昨日评论数 */
  yesterdayComments: number;
}

/** 创建评论参数 */
export interface CreateCommentRequest {
  /** 文章ID */
  articleId: number;
  /** 父评论ID */
  parentId?: number;
  /** 回复的用户ID */
  replyToUserId?: number | null;
  /** 评论内容 */
  content: string;
  /** IP地址 */
  ipAddress?: string;
  /** 用户代理 */
  userAgent?: string;
}

/** 创建评论响应数据 */
export interface CreateCommentResponse {
  /** 评论ID */
  commentId: number;
  /** 过滤后的内容 */
  content: string;
  /** 原始内容 */
  originalContent: string;
  /** 是否包含敏感词 */
  isSensitive: number;
  /** 敏感词类型 */
  sensitiveType?: string;
  /** 敏感词详细信息 */
  sensitiveWords?: string;
}

// ==================== API 接口函数 ====================

/** 创建评论 */
export const createCommentApi = (data: CreateCommentRequest) => {
  return http.request<ApiResponse<CreateCommentResponse>>(
    "post",
    "/admin/comments/create",
    { data }
  );
};

/** 敏感词检测 */
export const checkSensitiveWordsApi = (content: string) => {
  return http.request<ApiResponse<SensitiveCheckResponse>>(
    "post",
    "/admin/comments/check-sensitive",
    {
      data: content,
      headers: { "Content-Type": "text/plain" }
    }
  );
};

/** 标记敏感评论 */
export const markSensitiveCommentApi = (
  commentId: number,
  sensitiveType: string
) => {
  return http.request<ApiResponse>(
    "post",
    `/admin/comments/${commentId}/mark-sensitive`,
    {
      data: { sensitiveType }
    }
  );
};

/** 取消敏感标记 */
export const unmarkSensitiveCommentApi = (commentId: number) => {
  return http.request<ApiResponse>(
    "post",
    `/admin/comments/${commentId}/unmark-sensitive`
  );
};

/** 分页查询评论列表 */
export const getCommentListApi = (params: CommentListQuery) => {
  return http.request<ApiResponse<PageResponse<CommentInfo>>>(
    "get",
    "/admin/comments/list",
    { params }
  );
};

/** 删除评论 */
export const deleteCommentApi = (commentId: number) => {
  return http.request<ApiResponse>("delete", `/admin/comments/${commentId}`);
};

/** 批量操作评论 */
export const batchOperateCommentsApi = (params: BatchOperationParams) => {
  return http.request<ApiResponse>("post", "/admin/comments/batch", {
    data: params
  });
};

/** 获取评论树 */
export const getCommentTreeApi = (articleId?: number, rootId?: number) => {
  const params: any = {};
  if (articleId) params.articleId = articleId;
  if (rootId) params.rootId = rootId;

  return http.request<ApiResponse<CommentInfo[]>>(
    "get",
    "/admin/comments/tree",
    { params }
  );
};

/** 获取评论详情 */
export const getCommentDetailApi = (commentId: number) => {
  return http.request<ApiResponse<CommentInfo>>(
    "get",
    `/admin/comments/${commentId}`
  );
};

// ==================== 用户禁言管理接口 ====================

/** 禁言用户 */
export const banUserApi = (params: UserBanParams) => {
  return http.request<ApiResponse>("post", "/admin/user-ban/ban", {
    data: params
  });
};

/** 解除禁言 */
export const unbanUserApi = (userId: number, banType: BanType) => {
  return http.request<ApiResponse>("post", "/admin/user-ban/unban", {
    params: { userId, banType }
  });
};

/** 批量解除禁言 */
export const batchUnbanUsersApi = (userIds: number[], banType: BanType) => {
  return http.request<ApiResponse>("post", "/admin/user-ban/batch-unban", {
    params: { userIds: userIds.join(","), banType }
  });
};

/** 检查用户禁言状态 */
export const checkUserBanStatusApi = (userId: number, banType: BanType) => {
  return http.request<ApiResponse<boolean>>("get", "/admin/user-ban/check", {
    params: { userId, banType }
  });
};

/** 获取用户禁言状态 */
export const getUserBanStatusApi = (userId: number) => {
  return http.request<ApiResponse<UserBanStatus>>(
    "get",
    `/admin/user-ban/status/${userId}`
  );
};

// ==================== 统计和查询接口 ====================

/** 获取评论统计信息 */
export const getCommentStatisticsApi = () => {
  return http.request<ApiResponse<CommentStatistics>>(
    "get",
    "/admin/comments/statistics"
  );
};

/** 获取评论状态分布 */
export const getCommentStatusDistributionApi = () => {
  return http.request<ApiResponse<Record<string, number>>>(
    "get",
    "/admin/comments/status-distribution"
  );
};

/** 获取敏感词类型分布 */
export const getSensitiveTypeDistributionApi = () => {
  return http.request<ApiResponse<Record<string, number>>>(
    "get",
    "/admin/comments/sensitive-type-distribution"
  );
};

/** 获取禁言统计信息 */
export const getBanStatisticsApi = () => {
  return http.request<ApiResponse<Record<string, number>>>(
    "get",
    "/admin/user-ban/statistics"
  );
};

/** 最新评论查询参数 */
export interface LatestCommentsQuery {
  /** 页码 */
  current?: number;
  /** 每页大小 */
  size?: number;
  /** 文章ID */
  articleId?: number;
  /** 用户ID */
  userId?: number;
  /** 评论状态 */
  status?: CommentStatus;
  /** 是否包含敏感评论 */
  includeSensitive?: boolean;
  /** 开始时间 */
  startTime?: string;
  /** 结束时间 */
  endTime?: string;
  /** 关键词搜索 */
  keyword?: string;
  /** 是否只查询顶级评论 */
  onlyTopLevel?: boolean;
  /** 最小点赞数 */
  minLikeCount?: number;
  /** 最小回复数 */
  minReplyCount?: number;
}

/** 热门评论查询参数 */
export interface PopularCommentsQuery extends LatestCommentsQuery {
  /** 点赞权重 */
  likeWeight?: number;
  /** 回复权重 */
  replyWeight?: number;
  /** 最小热度分数 */
  minHotScore?: number;
  /** 时间范围类型 */
  timeRange?: "today" | "week" | "month" | "all";
}

/** 获取最新评论列表 */
export const getLatestCommentsApi = (params?: LatestCommentsQuery) => {
  return http.request<ApiResponse<PageResponse<CommentInfo>>>(
    "get",
    "/admin/comments/latest",
    { params }
  );
};

/** 获取热门评论列表 */
export const getPopularCommentsApi = (params?: PopularCommentsQuery) => {
  return http.request<ApiResponse<PageResponse<CommentInfo>>>(
    "get",
    "/admin/comments/popular",
    { params }
  );
};

/** 获取敏感评论数量 */
export const getSensitiveCountApi = () => {
  return http.request<ApiResponse<number>>(
    "get",
    "/admin/comments/sensitive-count"
  );
};

/** 搜索评论 */
export const searchCommentsApi = (
  keyword: string,
  current: number = 1,
  size: number = 10
) => {
  return http.request<ApiResponse<PageResponse<CommentInfo>>>(
    "get",
    "/admin/comments/search",
    {
      params: { keyword, current, size }
    }
  );
};

/** 获取用户评论 */
export const getUserCommentsApi = (
  userId: number,
  current: number = 1,
  size: number = 10
) => {
  return http.request<ApiResponse<PageResponse<CommentInfo>>>(
    "get",
    `/admin/comments/user/${userId}`,
    {
      params: { current, size }
    }
  );
};

/** 获取文章评论 */
export const getArticleCommentsApi = (
  articleId: number,
  current: number = 1,
  size: number = 10
) => {
  return http.request<ApiResponse<PageResponse<CommentInfo>>>(
    "get",
    `/admin/comments/article/${articleId}`,
    {
      params: { current, size }
    }
  );
};

/** 根据IP获取评论 */
export const getCommentsByIpApi = (
  ipAddress: string,
  current: number = 1,
  size: number = 10
) => {
  return http.request<ApiResponse<PageResponse<CommentInfo>>>(
    "get",
    `/admin/comments/ip/${ipAddress}`,
    {
      params: { current, size }
    }
  );
};

// ==================== 工具函数 ====================

/** 评论管理工具类 */
export class CommentManagementUtils {
  /** 获取评论状态文本 */
  static getStatusText(status: number): string {
    const statusMap: Record<number, string> = {
      0: "已删除",
      1: "正常显示"
    };
    return statusMap[status] || "未知状态";
  }

  /** 获取状态标签类型 */
  static getStatusTagType(
    status: number
  ): "success" | "info" | "warning" | "danger" | "primary" {
    const typeMap: Record<
      number,
      "success" | "info" | "warning" | "danger" | "primary"
    > = {
      0: "danger",
      1: "success"
    };
    return typeMap[status] || "info";
  }

  /** 获取敏感词类型文本 */
  static getSensitiveTypeText(type: string | null): string {
    if (!type) return "敏感内容";

    const typeMap: Record<string, string> = {
      profanity: "脏话",
      politics: "政治敏感",
      advertisement: "广告",
      violence: "暴力内容",
      illegal: "违法内容",
      spam: "垃圾信息"
    };
    return typeMap[type] || type;
  }

  /** 获取敏感词类型颜色 */
  static getSensitiveTypeColor(type: string | null): string {
    if (!type) return "#F56C6C";

    const colorMap: Record<string, string> = {
      profanity: "#F56C6C",
      politics: "#E6A23C",
      advertisement: "#409EFF",
      violence: "#F56C6C",
      illegal: "#F56C6C",
      spam: "#909399"
    };
    return colorMap[type] || "#F56C6C";
  }

  /** 获取禁言类型文本 */
  static getBanTypeText(type: BanType): string {
    const typeMap = {
      [BanType.COMMENT]: "禁止评论",
      [BanType.LOGIN]: "禁止登录",
      [BanType.ALL]: "全站禁言"
    };
    return typeMap[type] || "未知类型";
  }

  /** 获取批量操作类型文本 */
  static getBatchOperationText(type: string): string {
    const textMap: Record<string, string> = {
      delete: "删除",
      mark_sensitive: "标记敏感",
      unmark_sensitive: "取消敏感标记"
    };
    return textMap[type] || "未知操作";
  }

  /** 格式化时间 */
  static formatTime(time: string): string {
    if (!time) return "-";
    const date = new Date(time);
    const now = new Date();
    const diff = now.getTime() - date.getTime();

    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;

    if (diff < minute) {
      return "刚刚";
    } else if (diff < hour) {
      return Math.floor(diff / minute) + "分钟前";
    } else if (diff < day) {
      return Math.floor(diff / hour) + "小时前";
    } else {
      return date.toLocaleDateString();
    }
  }

  /** 截取评论内容 */
  static truncateContent(content: string, maxLength: number = 50): string {
    if (!content) return "";
    if (content.length <= maxLength) return content;
    return content.substring(0, maxLength) + "...";
  }

  /** 构建评论树形结构 */
  static buildCommentTree(comments: CommentInfo[]): CommentInfo[] {
    const commentMap = new Map<number, CommentInfo>();
    const rootComments: CommentInfo[] = [];

    // 创建评论映射
    comments.forEach(comment => {
      comment.children = [];
      commentMap.set(comment.id, comment);
    });

    // 构建树形结构
    comments.forEach(comment => {
      if (comment.parentId === 0) {
        rootComments.push(comment);
      } else {
        const parent = commentMap.get(comment.parentId);
        if (parent) {
          parent.children!.push(comment);
        }
      }
    });

    return rootComments;
  }

  /** 计算评论层级 */
  static calculateCommentLevel(path: string): number {
    if (!path) return 1;
    return path.split("/").length;
  }

  /** 验证禁言参数 */
  static validateBanParams(params: UserBanParams): string[] {
    const errors: string[] = [];

    if (!params.userId) {
      errors.push("用户ID不能为空");
    }

    if (!params.banType) {
      errors.push("禁言类型不能为空");
    }

    if (
      !params.isPermanent &&
      (!params.banDuration || params.banDuration <= 0)
    ) {
      errors.push("禁言时长必须大于0");
    }

    if (!params.banReason?.trim()) {
      errors.push("禁言原因不能为空");
    }

    return errors;
  }

  /** 格式化禁言时长 */
  static formatBanDuration(minutes: number): string {
    if (minutes < 60) {
      return `${minutes}分钟`;
    } else if (minutes < 1440) {
      return `${Math.floor(minutes / 60)}小时`;
    } else {
      return `${Math.floor(minutes / 1440)}天`;
    }
  }

  /** 检查是否可以执行操作 */
  static canPerformOperation(status: number, operation: string): boolean {
    const operationMap: Record<number, string[]> = {
      0: [], // 已删除的评论不能执行任何操作
      1: ["delete", "mark_sensitive", "unmark_sensitive"] // 正常评论可以删除和标记敏感
    };

    return operationMap[status]?.includes(operation) || false;
  }

  /** 将数字转换为布尔值 (用于处理后端返回的 0/1 值) */
  static toBool(value: number | boolean | null | undefined): boolean {
    if (typeof value === "boolean") return value;
    if (typeof value === "number") return value > 0;
    return false;
  }

  /** 检查评论是否敏感 */
  static isSensitiveComment(comment: CommentInfo): boolean {
    return this.toBool(comment.isSensitive);
  }
}
